#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
任务管理API路由
"""

from flask import Blueprint, request, jsonify
from models.task import Task
from models.staff import Staff
from database import db
from utils.decorators import admin_required, token_required
from datetime import datetime, timedelta
from sqlalchemy import or_, and_
import jwt

task_bp = Blueprint('task', __name__)

@task_bp.route('/', methods=['GET'])
@admin_required
def get_task_list(admin):
    """获取任务列表（管理员）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        status = request.args.get('status', '')
        priority = request.args.get('priority', '')
        staff_id = request.args.get('staff_id', type=int)
        
        query = Task.query
        
        if search:
            query = query.filter(or_(
                Task.title.like(f'%{search}%'),
                Task.description.like(f'%{search}%')
            ))
        
        if status:
            query = query.filter(Task.status == status)
        
        if priority:
            query = query.filter(Task.priority == priority)
            
        if staff_id:
            query = query.filter(Task.staff_id == staff_id)
        
        pagination = query.order_by(Task.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        task_list = pagination.items
        
        return jsonify({
            'success': True,
            'data': {
                'tasks': [task.to_dict() for task in task_list],
                'pagination': {
                    'page': page,
                    'pages': pagination.pages,
                    'per_page': per_page,
                    'total': pagination.total,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取任务列表失败: {str(e)}'}), 500

@task_bp.route('/my', methods=['GET'])
def get_my_tasks():
    """获取我的任务列表（工作人员）"""
    try:
        # 从请求头获取token
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return jsonify({'success': False, 'message': '未提供认证信息'}), 401
        
        token = auth_header.split(' ')[1]
        
        try:
            payload = jwt.decode(token, 'billiard-jwt-secret', algorithms=['HS256'])
            staff_id = payload.get('staff_id')
        except jwt.ExpiredSignatureError:
            return jsonify({'success': False, 'message': '登录已过期'}), 401
        except jwt.InvalidTokenError:
            return jsonify({'success': False, 'message': '无效的认证信息'}), 401
        
        status = request.args.get('status', '')
        
        query = Task.query.filter_by(staff_id=staff_id)
        
        if status:
            query = query.filter(Task.status == status)
        
        tasks = query.order_by(Task.created_at.desc()).all()
        
        return jsonify({
            'success': True,
            'data': {
                'tasks': [task.to_dict() for task in tasks]
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取任务列表失败: {str(e)}'}), 500

@task_bp.route('/', methods=['POST'])
@admin_required
def create_task(admin):
    """创建任务"""
    try:
        data = request.get_json()
        
        task = Task(
            title=data['title'],
            description=data['description'],
            staff_id=data['staff_id'],
            priority=data.get('priority', 'medium'),
            due_date=datetime.strptime(data['due_date'], '%Y-%m-%d %H:%M:%S') if data.get('due_date') else None,
            assigned_by=admin.id
        )
        
        db.session.add(task)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '任务创建成功',
            'data': task.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'创建任务失败: {str(e)}'}), 500

@task_bp.route('/<int:task_id>', methods=['PUT'])
def update_task(task_id):
    """更新任务"""
    try:
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'message': '任务不存在'}), 404
        
        data = request.get_json()
        
        # 检查权限（管理员或任务分配的员工可以更新）
        auth_header = request.headers.get('Authorization')
        if auth_header and auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
            try:
                payload = jwt.decode(token, 'billiard-jwt-secret', algorithms=['HS256'])
                staff_id = payload.get('staff_id')
                if task.staff_id != staff_id:
                    # 检查是否是管理员
                    admin_token = request.headers.get('Admin-Token')
                    if not admin_token:
                        return jsonify({'success': False, 'message': '权限不足'}), 403
            except jwt.InvalidTokenError:
                return jsonify({'success': False, 'message': '无效的认证信息'}), 401
        
        if 'title' in data:
            task.title = data['title']
        if 'description' in data:
            task.description = data['description']
        if 'status' in data:
            task.status = data['status']
            if data['status'] == 'completed':
                task.completed_at = datetime.now()
        if 'priority' in data:
            task.priority = data['priority']
        if 'due_date' in data:
            task.due_date = datetime.strptime(data['due_date'], '%Y-%m-%d %H:%M:%S') if data['due_date'] else None
        
        task.updated_at = datetime.now()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '任务更新成功',
            'data': task.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'更新任务失败: {str(e)}'}), 500

@task_bp.route('/<int:task_id>', methods=['DELETE'])
@admin_required
def delete_task(admin, task_id):
    """删除任务"""
    try:
        task = Task.query.get(task_id)
        if not task:
            return jsonify({'success': False, 'message': '任务不存在'}), 404
        
        db.session.delete(task)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '任务删除成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'删除任务失败: {str(e)}'}), 500

@task_bp.route('/stats', methods=['GET'])
def get_task_stats():
    """获取任务统计（工作人员用）"""
    try:
        # 从请求头获取token
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return jsonify({'success': False, 'message': '未提供认证信息'}), 401
        
        token = auth_header.split(' ')[1]
        
        try:
            payload = jwt.decode(token, 'billiard-jwt-secret', algorithms=['HS256'])
            staff_id = payload.get('staff_id')
        except jwt.ExpiredSignatureError:
            return jsonify({'success': False, 'message': '登录已过期'}), 401
        except jwt.InvalidTokenError:
            return jsonify({'success': False, 'message': '无效的认证信息'}), 401
        
        today = datetime.now().date()
        tomorrow = today + timedelta(days=1)
        
        # 今日任务统计
        pending_tasks = Task.query.filter(
            Task.staff_id == staff_id,
            Task.status == 'pending',
            Task.created_at >= today,
            Task.created_at < tomorrow
        ).count()
        
        completed_tasks = Task.query.filter(
            Task.staff_id == staff_id,
            Task.status == 'completed',
            Task.completed_at >= today,
            Task.completed_at < tomorrow
        ).count()
        
        # 模拟工作时长（实际应该根据打卡记录计算）
        work_hours = 8.0  # 默认8小时
        
        return jsonify({
            'success': True,
            'data': {
                'pending_tasks': pending_tasks,
                'completed_tasks': completed_tasks,
                'work_hours': work_hours
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取统计数据失败: {str(e)}'}), 500